/* ConnectionHandler.java
 * Jeremiah Theurer
 * This file contains code to handle the connections for VOIP app.
*/

import java.net.*;
import java.io.*;
import java.util.*;

public class ConnectionHandler implements Runnable
{
	Socket socket;
	public LinkedList<User> directory;
	public ConnectionHandler(Socket sock, LinkedList<User> dir)
	{
		socket = sock;
		directory = dir;
	}
	
	public void run()
	{
		try
		{
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			String input, userName, ipAddr;
			
			while(true)
			{
				if(in.ready())
				{
					input = in.readLine();
					if(input.equals("login"))
					{
						userName = in.readLine();
						ipAddr = in.readLine();
						System.out.println("User: " + userName + " IP: " + ipAddr);
						User obj = new User(userName,ipAddr);
						boolean allow = false;
						for(int i = 0; i < directory.size(); i++)
						{
							if(directory.get(i).userName.equals(userName))
							{
								allow = false;
								break;
							}
							if(i == directory.size()-1)
							{
								allow = true;
							}
						}
						if(directory.size() == 0 || allow)
						{
							directory.add(obj);
							System.out.println(userName + " joined.");
						}
					}
					if(input.equals("logout"))
					{
						userName = in.readLine();
						ipAddr = in.readLine();
						for(int i = 0; i < directory.size(); i++)
						{
							if(directory.get(i).userName.equals(userName))
							{
								directory.remove(i);
								System.out.println(userName + " left.");
							}
						}
					}
					if(input.equals("get users"))
					{
						String curUser = in.readLine();
						out.println(directory.size());
						for(int i = 0; i < directory.size(); i++)
						{
							if(!(directory.get(i).userName).equals(curUser))
							{
								out.println(directory.get(i).userName);
							}
						}
					}
					if(input.equals("get ip"))
					{
						userName = in.readLine();
						for(int i = 0; i < directory.size(); i++)
						{
							if((directory.get(i).userName).equals(userName))
							{
								out.println(directory.get(i).ipAddr);
							}
						}
					}
				}
				if(socket.isClosed())
				{
					return;
				}
			}
		}
		catch(IOException e)
		{
			System.out.println("Error in Connectino Handler");
		}
	}
}